package ctype

import (
	"encoding/json"
	"database/sql/driver"
	"errors"
)

// NullRawMessage represents a json.RawMessage that may be null.
// NullRawMessage implements the Scanner interface so
// it can be used as a scan destination, similar to NullString.
type NullRawMessage struct {
	RawMessage json.RawMessage
	Valid bool // Valid is true if JSON is not NULL
}

// Scan implements the Scanner interface.
func (n *NullRawMessage) Scan(value interface{}) error {
	if value == nil {
		n.RawMessage, n.Valid = json.RawMessage{}, false
		return nil
	}
	buf, ok := value.([]byte)

	if !ok {
		return errors.New("canot parse to bytes")
	}

	n.RawMessage, n.Valid = buf, true

	return nil
}

// Value implements the driver Valuer interface.
func (n NullRawMessage) Value() (driver.Value, error) {
	if !n.Valid {
		return nil, nil
	}
	return n.RawMessage.MarshalJSON()
}

// // MarshalJSON returns m as the JSON encoding of m.
// func (n NullRawMessage) MarshalJSON() ([]byte, error) {
// 	if !n.Valid {
// 		return []byte("null"), nil
// 	}
// 	return m, nil
// }

// // UnmarshalJSON sets *m to a copy of data.
// func (n *NullRawMessage) UnmarshalJSON(data []byte) error {
// 	if n == nil {
// 		return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
// 	}
// 	*m = append((*m)[0:0], data...)
// 	return nil
// }